﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using ZhCun.DbCore.DBHelper;

namespace ZhCun.DbCore.Exceptions
{
    public class DbHelperException : Exception
    {
        /// <summary>
        /// 用于自定义异常，非系统抛出的异常
        /// </summary>
        protected internal DbHelperException(string message, IDbHelper dbHelper)
             : this(message, dbHelper, null)
        { }
        /// <summary>
        /// 系统抛出的异常来构造异常对象
        /// </summary>
        protected internal DbHelperException(string message, IDbHelper dbHelper, Exception innerException)
             : base(message, innerException)
        {
            ConnectionString = dbHelper.ConnStr;
            if (dbHelper.DbCommandObj != null)
            {
                CommandText = dbHelper.DbCommandObj.CommandText;
                if (dbHelper.DbCommandObj.Parameters != null)
                {
                    CommandParams = new Dictionary<string, object>();
                    StringBuilder sb = new StringBuilder();
                    foreach (DbParameter item in dbHelper.DbCommandObj.Parameters)
                    {
                        CommandParams[item.ParameterName] = item.Value;
                        sb.AppendFormat("{0}: {1}\r\n", item.ParameterName, item.Value);
                    }
                    CommandParamRemark = sb.ToString();
                }
            }
        }
        /// <summary>
        /// 返回连接字符串
        /// </summary>
        public string ConnectionString { get; private set; }
        /// <summary>
        /// 返回执行的sql文本
        /// </summary>
        public string CommandText { get; private set; }
        /// <summary>
        /// 返回执行sql命令的参数列表
        /// </summary>
        public Dictionary<string, object> CommandParams { get; private set; }
        /// <summary>
        /// 返回执sql命令的参数列表字符串说明
        /// </summary>
        public string CommandParamRemark { get; private set; }
        /// <summary>
        /// 返回执行sql命令及参数说明
        /// </summary>
        public string ExecRemark
        {
            get
            {
                return string.Format("SQL：{0}\r\nParameters：{1}", CommandText, CommandParamRemark);
            }
        }
    }
}